package com.gxuwz.leaveSystem.dao;

import com.gxuwz.leaveSystem.entity.Department;
import com.gxuwz.leaveSystem.entity.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;

public class DepartmentDao {

    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 添加
     * @param dp
     * @return
     */
    public int add(Department dp){
        String sql = "insert into sys_department(depID, depName) value(?,?)";
        Object[] obj = new Object[] {
                dp.getDepID(),
                dp.getDepName()
        };
        int num = this.jdbcTemplate.update(sql,obj);
        return num;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public int delete(String id){
        String sql = "delete from sys_department where depID=?";
        int num = this.jdbcTemplate.update(sql,id);
        return num;
    }

    /**
     * 修改
     * @param dp
     * @return
     */

    public int update(Department dp){
        String sql = "update sys_department set depName = ? where depID = ?";
        Object[] up = new Object[] {
                dp.getDepName(),
                dp.getDepID()
        };
        int num = this.jdbcTemplate.update(sql,up);
        return num;
    }

    /**
     * 根据id查列表
     * @param id
     * @return
     */

    public Department findByid(String id){
        String sql = "select * from sys_department where depID = ?";
        //通过rowmapper返回单行记录
        RowMapper<Department> rowMapper = new BeanPropertyRowMapper<Department>(Department.class);
        // 使用query方法返回一个List
        List<Department> dp = this.jdbcTemplate.query(sql, rowMapper, id);

        // 检查List是否为空
        if (dp.isEmpty()) {
            return null; // 或者返回一个默认的User对象
        } else {
            return dp.get(0);
        }
    }

    /**
     * 查询全部
     * @return
     */
    public List<Department> findAll(){
        String sql = "select * from sys_department";
        RowMapper<Department> rowMapper = new BeanPropertyRowMapper<Department>(Department.class);
        return  this.jdbcTemplate.query(sql,rowMapper);
    }

    /**
     * 根据关键字搜索
     * @param keyword
     * @return
     */
    public List<Department> search(String keyword) {
        String sql = "SELECT * FROM sys_department WHERE sys_department.depID LIKE ? OR sys_department.depName LIKE ?";
        return jdbcTemplate.query(sql, new Object[]{"%" + keyword + "%", "%" + keyword + "%"}, new BeanPropertyRowMapper<>(Department.class));
    }
}
